<template>
	<el-dialog
		:title="type == 'add' ? '添加用户' : '修改用户信息'"
		v-model="state.visible"
		width="400px"
	>
		<el-form :model="state.ruleForm" :rules="state.rules" ref="formRef" label-width="100px" class="good-form">
			<el-form-item label="图片" prop="url">
				<el-upload
					class="avatar-uploader"
					:action="state.uploadImgServer"
					accept="jpg,jpeg,png"
					:headers="{ 'hw-token' : state.token}"
					:show-file-list="false"
					:before-upload="handleBeforeUpload"
					:on-success="handleUrlSuccess"
				>
					<img style="width: 200px; height: 100px; border: 1px solid #e9e9e9;" v-if="state.ruleForm.url"
					     :src="state.ruleForm.url" class="avatar">
					<el-icon v-else class="avatar-uploader-icon">
						<Plus/>
					</el-icon>
				</el-upload>
			</el-form-item>
			<el-form-item label="用户名" prop="userName">
				<el-input type="text" v-model="state.ruleForm.userName"></el-input>
			</el-form-item>
			<el-form-item label="用户手机" prop="userPhone">
				<el-input type="number" v-model="state.ruleForm.userPhone"></el-input>
			</el-form-item>
			<el-form-item label="用户密码" prop="userPassword">
				<el-input type="number" v-model="state.ruleForm.userPassword"></el-input>
			</el-form-item>
			<el-form-item label="用户角色" prop="roleIds">
				<el-checkbox-group v-model="state.ruleForm.roleIds">
					<template v-for="item in state.roleList">
						<el-checkbox :label="item.roleId" :value="item.roleId">{{ item.roleName }}</el-checkbox>
					</template>

				</el-checkbox-group>
			</el-form-item>
		</el-form>
		<template #footer>
      <span class="dialog-footer">
        <el-button @click="state.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
		</template>
	</el-dialog>
</template>

<script setup>
import {reactive, ref} from 'vue';
import {userAdd, userDetail, userUpdate} from '@/api/user';
import {getAllRoles} from '@/api/role';
import {localGet, ossPath, uploadImgServer} from '@/utils';
import {ElMessage} from 'element-plus';
import md5 from 'js-md5';

const props = defineProps({
  type: String,
  reload: Function
});

const formRef = ref(null);
const state = reactive({
  uploadImgServer,
  token: localGet('token') || '',
  visible: false,
  roleList: [],
  ruleForm: {
    id: '',
    url: '',
    userName: '',
    userPhone: '',
    userPassword: '',
    roleIds: []
  },
  rules: {
    url: [
      {required: 'true', message: '图片不能为空', trigger: ['change']}
    ],
    userName: [
      {required: 'true', message: '用户名不能为空', trigger: ['change']}
    ],
    userPhone: [
      {required: 'true', message: '用户手机号不能为空', trigger: ['change']}
    ],
    userPassword: [
      {required: 'true', message: '用户密码不能为空', trigger: ['change']}
    ],
    roleIds: [
      {required: 'true', message: '用户角色不能为空', trigger: ['change']}
    ]
  },
  id: ''
});
// 获取详情
const getDetail = async (id) => {
  console.log('详情', id);
  await userDetail(id).then(res => {
    console.log('详情', res.data.data.userName);
    state.ruleForm = {
      id: res.data.data.id,
      userImg: res.data.data.userImg,
      url: res.data.data.userImg,
      userName: res.data.data.userName,
      userPhone: res.data.data.userPhone,
      userPassword: '',
      roleIds: []
    };
  });
};
const handleBeforeUpload = (file) => {
  const sufix = file.name.split('.')[1] || '';
  if (!['jpg', 'jpeg', 'png'].includes(sufix)) {
    ElMessage.error('请上传 jpg、jpeg、png 格式的图片');
    return false;
  }
};
// 上传图片
const handleUrlSuccess = (val) => {
  // 拼接文件路径
  state.ruleForm.url = ossPath + val.data || '';
  state.ruleForm.userImg = ossPath + val.data || '';
};
// 开启弹窗
const open = async (row) => {
  await getAllRoles().then(res => {
    console.log('角色', res.data.data);
    state.roleList = res.data.data;
    console.log('角色', state.roleList);
  });
  state.visible = true;
  console.log('id', row);
  if (row) {
    getDetail(row.id);
  } else {
    state.ruleForm = {
      url: '',
      userName: '',
      userPhone: '',
      userImg: '',
      userPassword: '',
      roleIds: []
    };
  }
};
// 关闭弹窗
const close = () => {
  state.visible = false;
};
const submitForm = () => {
  console.log(formRef.value.validate);
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (props.type === 'add') {
        await userAdd(
          state.ruleForm
        ).then(() => {
          ElMessage.success('添加成功');
          state.visible = false;
          if (props.reload) props.reload();
        });
      } else {
        state.ruleForm.userPassword = md5(state.ruleForm.userPassword);
        await userUpdate(
          state.ruleForm
        ).then(() => {
          ElMessage.success('修改成功');
          state.visible = false;
          if (props.reload) props.reload();
        });
      }
    }
  });
};
defineExpose({open, close});
</script>

<style scoped>
.avatar-uploader {
    width: 100px;
    height: 100px;
    color: #ddd;
    font-size: 30px;
}

.avatar-uploader >>> .el-upload {
    width: 100%;
    text-align: center;
}

.avatar-uploader-icon {
    display: block;
    width: 100%;
    height: 100%;
    border: 1px solid #e9e9e9;
    padding: 32px 17px;
}
</style>
